import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export const useAiApiStore = defineStore('aiApi', () => {
  const API_URL = 'https://open.bigmodel.cn/api/paas/v4/chat/completions'
  const API_KEY = import.meta.env.VITE_API_KEY // 建议从环境变量获取
  
  const loading = ref(false)
  const error = ref(null)

  // 构建API所需的消息格式
  const formatMessages = (messages) => {
    return messages.map( msg => {
      const content = []
      
      if (msg.image_code) {
        content.push({
          type: 'image_url',
          image_url: {
            url: msg.image_code
          }
        })
      }
      
      if (msg.content) {
        content.push({
          type: 'text',
          text: msg.content
        })
      }
      
      return {
        role: msg.type === 'user' ? 'user' : 'assistant',
        content: content
      }
    })
  }

  // 发送请求到智谱AI
  const sendRequest = async (messageHistory) => {
    loading.value = true
    error.value = null
    
    try {
           
      // 格式化历史消息
      const formattedMessages = formatMessages(messageHistory)
      
      const response = await axios.post(API_URL, {
        model: 'glm-4v-flash',
        messages: formattedMessages
      }, {
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json'
        }
      })

      // 处理响应
      if (response.data && response.data.choices && response.data.choices[0]) {
        const assistantMessage = response.data.choices[0].message
        return {
          role: 'assistant',
          content: assistantMessage.content // 获取文本内容
        }
      } else {
        throw new Error('无效的API响应')
      }

    } catch (err) {
      console.error('API请求错误:', err)
      error.value = err.message || '请求失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    error,
    sendRequest
  }
})
